package com.apes.framework.plugin.workflow.domain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.websocket.WsMessage;
import com.apes.framework.plugin.websocket.WsPublisher;
import com.apes.framework.util.MapUtil;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("carbonCopyMessageService")
public class CarbonCopyMessageService extends DomainService {

    @Autowired
    CarbonCopyMessageRepository carbonCopyMessageRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    WsPublisher wsPublisher;

    public CarbonCopyMessage create(SimpleRequest request) {
        CarbonCopyMessage carbonCopyMessage = request.getO(CarbonCopyMessage.class);
        return carbonCopyMessageRepository.saveAndFlush(carbonCopyMessage);
    }

    public CarbonCopyMessage update(SimpleRequest request) {
        CarbonCopyMessage carbonCopyMessage = request.getO(CarbonCopyMessage.class);
        return carbonCopyMessageRepository.saveAndFlush(carbonCopyMessage);
    }


    public List<CarbonCopyMessage> findAllByUserId(SimpleRequest request){
        return carbonCopyMessageRepository.findAllByToTargetId(request.get("userId"));
    }

    public List<CarbonCopyMessage> findAllUncheckedByUserId(SimpleRequest request){
        return carbonCopyMessageRepository.findAllByToTargetIdAndCheckedIsFalse(request.get("userId"));
    }


    // 监听抄送消息，并发送到客户端
    @Listener(topic = "event:wf.carbonCopy")
    public void sendCarbonCopyMsg(SimpleRequest request){
        JSONObject sourceJson = request.getJO();
        JSONArray toArray = sourceJson.getJSONArray("to_id");

        for( int i = 0, length = toArray.size(); i < length; i++ ){
            JSONObject toJson = toArray.getJSONObject(i);
            if( toJson.get("id") == null ) continue;
            CarbonCopyMessage carbonCopyMessage = initInstance(toJson, sourceJson);

            WsMessage wsMessage = new WsMessage();


            wsMessage.setTo(carbonCopyMessage.getToTarget().getId().toString());
            wsMessage.setBody(JSON.toJSONString(mapper(
                    "topic", "ws.wf.carbonCopy",
                    "message", MapUtil.mapped(carbonCopyMessage)
            )));
            wsPublisher.publish(wsMessage);
        }
    }

    /***
     * 初始化一个实例
     * @param toJson
     * @param sourceJson
     * @return
     */
    private CarbonCopyMessage initInstance(JSONObject toJson, JSONObject sourceJson) {
        CarbonCopyMessage carbonCopyMessage = new CarbonCopyMessage();
        User toTarget = userRepository.findOne(toJson.getInteger("id"));
        User fromOrigin = userRepository.findOne(sourceJson.getInteger("from_id"));
        carbonCopyMessage.setToTarget(toTarget);
        carbonCopyMessage.setFromOrigin(fromOrigin);
        carbonCopyMessage.setSourceBusinessKey(sourceJson.getString("sourceBusinessKey"));
        carbonCopyMessage.setSourceBusinessType(sourceJson.getString("sourceBusinessType"));
        carbonCopyMessage.setProcessDefinitionName(sourceJson.getString("processDefinitionName"));
        carbonCopyMessage.setFormId(sourceJson.getString("formId"));
        carbonCopyMessage.setApi(sourceJson.getString("api"));
        carbonCopyMessage.setOperate(sourceJson.getString("operate"));
        carbonCopyMessage.setContent(sourceJson.getString("content"));
        carbonCopyMessage.setChecked(sourceJson.getBoolean("checked"));
        return carbonCopyMessageRepository.saveAndFlush(carbonCopyMessage);
    }

    /**
     * 处理超过7天的消息未已阅
     */
    public void moreServenDayMessage(SimpleRequest request){
        List<CarbonCopyMessage> list = carbonCopyMessageRepository.findAllMoreSevenDayMessage();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setChecked(true);
            list.get(i).setContent(list.get(i).getContent() + " || 消息超过7天，系统自动设置未已阅");
        }
        carbonCopyMessageRepository.saveAll(list);
    }

}


